package com.sl.core.engine.classloader;

import cn.hutool.core.util.BooleanUtil;
import org.apache.hop.core.plugins.HopURLClassLoader;

import java.io.IOException;
import java.net.URL;
import java.util.Enumeration;
import java.util.NoSuchElementException;
import java.util.Objects;

public class ProcessClassLoader extends HopURLClassLoader {
    public ProcessClassLoader(URL[] url, ClassLoader classLoader) {
        super(url, classLoader);
    }

    public Enumeration<URL> getResources(String name, Boolean findParentFlag) throws IOException {
        if (BooleanUtil.isTrue(findParentFlag)) {
            return super.getResources(name);
        }
        Objects.requireNonNull(name);
        @SuppressWarnings("unchecked") Enumeration<URL>[] tmp = (Enumeration<URL>[]) new Enumeration<?>[1];
//        tmp[0] = ClassLoaders.bootLoader().findResources(name);
        tmp[0] = findResources(name);

        return new CompoundEnumeration<>(tmp);
    }

    final class CompoundEnumeration<E> implements Enumeration<E> {
        private final Enumeration<E>[] enums;
        private int index;

        public CompoundEnumeration(Enumeration<E>[] enums) {
            this.enums = enums;
        }

        private boolean next() {
            while (index < enums.length) {
                if (enums[index] != null && enums[index].hasMoreElements()) {
                    return true;
                }
                index++;
            }
            return false;
        }

        public boolean hasMoreElements() {
            return next();
        }

        public E nextElement() {
            if (!next()) {
                throw new NoSuchElementException();
            }
            return enums[index].nextElement();
        }
    }
}
